package com.axjy.user.service.impl;

import com.axjy.comm.pojo.TpImage;
import com.axjy.comm.pojo.TpLinkUser;
import com.axjy.comm.pojo.TpUser;
import com.axjy.comm.util.TokenUtil;
import com.axjy.comm.util.TpContext;
import com.axjy.user.feign.ImageFeignClient;
import com.axjy.user.mapper.LinkUserMapper;
import com.axjy.user.mapper.UserMapper;
import com.axjy.user.service.UserService;
import com.axjy.user.vo.LinkUserVo;
import com.axjy.user.vo.TokenVo;
import com.axjy.user.vo.UserVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.annotation.Resources;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private ImageFeignClient imageFeignClient;

    @Resource
    private TokenUtil tokenUtil;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Resource
    private LinkUserMapper linkUserMapper;

    @Override
    public Object[] login(String phone, String password) {
        Object[] objs=new Object[2];
       TpUser tpUser=userMapper.findByPhoneAndPassword(phone,password);
        UserVo userVo=new UserVo();
        BeanUtils.copyProperties(tpUser,userVo);
        userVo.setUserId(tpUser.getId());
        TpImage tpImage=imageFeignClient.findByTargetId(userVo.getUserId(),0,0);
        if(tpImage!=null){
            userVo.setImageId(tpImage.getId());
            userVo.setImgUrl(tpImage.getImgUrl());
        }
        objs[0]=userVo;
        TokenVo tokenVo=new TokenVo();
        tokenVo.setToken(tokenUtil.createToken(userVo.getUserId()));
        tokenVo.setGenTime(tokenUtil.getCreateTime());
        tokenVo.setExtTime(tokenUtil.getTtl());
        objs[1]=tokenVo;
        BoundValueOperations<String,String> operations= stringRedisTemplate.boundValueOps("token:"+userVo.getUserId());
        operations.set(tokenVo.getToken(),tokenVo.getExtTime(), TimeUnit.MINUTES);
        TpContext.setLoginUserTl(tpUser.getId());
        return objs;
    }

    @Override
    public List<LinkUserVo> queryLinkUser(Integer userId) {
        QueryWrapper<TpLinkUser> wrapper= Wrappers.query();
        wrapper.eq("user_id",userId);
        List<TpLinkUser> list= linkUserMapper.selectList(wrapper);
        return list.stream().map(tpLinkUser -> {
            LinkUserVo linkUserVo=new LinkUserVo();
            BeanUtils.copyProperties(tpLinkUser,linkUserVo);
            return linkUserVo;
        }).collect(Collectors.toList());
    }
}
